require_relative '../test_helper'

module Resources
  class PostsTest < Resources::Test
    def setup
      super # 重要
      @user = users(:one)
    end

    def test_get_posts_of_my_own
      header 'X-Token', @user.to_token
      get path('posts')
      assert last_response.ok?
      assert_equal({
        posts: [
          { id: 1, title: 'title 1', user_id: 1 },
          { id: 2, title: 'title 2', user_id: 1 }
        ]
      }.as_json, JSON.parse(last_response.body))
    end

    def test_get_posts_of_specified_user
      get path('users/2/posts')
      assert last_response.ok?
      assert_equal({
        posts: [
          { id: 3, title: 'title 3', user_id: 2 }
        ]
      }.as_json, JSON.parse(last_response.body))
    end

    def test_create_new_post
      header 'X-Token', @user.to_token
      post path('posts'),
           { post: attributes_for(:post, title: 'title created') }.to_json,
           { 'CONTENT_TYPE' => 'application/json' }
      assert last_response.created?
      assert_equal({
        post: {
          id: 4, title: 'title created', content: 'content', user_id: 1
        }
      }.as_json, JSON.parse(last_response.body))
    end

    def test_show_post
      get path('posts/1')
      assert last_response.ok?
      assert_equal({
        post: {
          id: 1, title: 'title 1', content: 'content 1', user_id: 1
        }
      }.as_json, JSON.parse(last_response.body))
    end

    def test_update_post
      header 'X-Token', @user.to_token
      put path('posts/1'),
          { post: { title: 'title updated', content: 'content updated' } }.to_json,
          { 'CONTENT_TYPE' => 'application/json' }
      assert last_response.ok?
      assert_equal({
        post: {
          id: 1, title: 'title updated', content: 'content updated', user_id: 1
        }
      }.as_json, JSON.parse(last_response.body))
    end

    def test_destroy_post
      header 'X-Token', @user.to_token
      delete path('posts/1')
      assert last_response.no_content?
      assert !Post.where(id: 1).exists?
    end
  end
end
